package com.szt.sy.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.szt.sy.config.security.authentication.provider.AdminAuthenticationProvider;
import com.szt.sy.service.system.menu.MenuService;
import com.szt.sy.service.system.user.UserService;

/***
 * web安全配置
 * 
 * @author wwy
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	@Qualifier("userPasswordEncoder")
	private PasswordEncoder passwordEncoder;
	
	@Bean("userPasswordEncoder")
	public PasswordEncoder passwordEncorder() {
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 定义认证信息提供者
		AdminAuthenticationProvider authenticationProvider = new AdminAuthenticationProvider(userService,
				passwordEncoder);
		authenticationProvider.setMenuService(menuService);
		auth.authenticationProvider(authenticationProvider).eraseCredentials(true);
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 配置表单登录
		http.formLogin().loginPage("/admin/login").loginProcessingUrl("/admin/login").defaultSuccessUrl("/admin/main");
		// 配置登出
		http.logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login");
		// 禁用csrf
		http.csrf().disable();
		// 允许iframe
		http.headers().frameOptions().sameOrigin();
		// 配置 rememberme功能
		http.rememberMe().rememberMeParameter("rememberMe").alwaysRemember(false).userDetailsService(userService)
				.key("fsafasfafafa-fafafa");
		http.authorizeRequests().antMatchers("/admin/login").permitAll();
		http.authorizeRequests().antMatchers("/admin/**").authenticated();
		http.authorizeRequests().antMatchers("/**").permitAll();
		
	}
	
	@Override
	public void configure(WebSecurity web) throws Exception {
		super.configure(web);
	}
	
}
